package cn.tedu.luban.order.webapi.consumer;

import cn.tedu.luban.commons.enums.order.OrderStatusEnum;
import cn.tedu.luban.commons.enums.order.ResultEnum;
import cn.tedu.luban.commons.pojo.order.dto.OrderMqDTO;
import cn.tedu.luban.commons.pojo.order.model.Order;
import cn.tedu.luban.order.service.IOrderService;
import cn.tedu.luban.order.webapi.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
@RocketMQMessageListener(
        topic = "${mq.topic.settle-success-topic:settle-success-topic}",
        consumerGroup = "${rocketmq.producer.group}")
public class SettleListener implements RocketMQListener<OrderMqDTO> {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IOrderService orderService;

    @Override
    public void onMessage(OrderMqDTO settleDTO) {
        log.info("结算中心成功回调: {}", settleDTO);
        String orderNo = settleDTO.getOrderNo();
        if (StringUtils.isEmpty(orderNo)) {
            log.error("结算回调,订单号为空, message: {}", settleDTO);
            throw new RuntimeException(ResultEnum.SETTLE_ORDER_NO_EMPTY.getMessage());
        }

        Order order = orderMapper.getOrderByOrderNo(orderNo);
        if (null == order) {
            log.error("结算回调,根据订单号查询不到, message: {}", settleDTO);
            throw new RuntimeException(ResultEnum.ORDER_EMPTY.getMessage());
        }

        if (!OrderStatusEnum.ORDER_SERVICE_SUCCESS_UN_SETTLE.getStatus().equals(order.getStatus())) {
            log.error("结算回调,订单状态不正确, message: {}", settleDTO);
            throw new RuntimeException(ResultEnum.SETTLE_CALL_ORDER_STATUS_ERROR.getMessage());
        }
        try {
            orderService.finishOrder(orderNo,settleDTO.getWorkerId());
        } catch (Exception e) {
            log.error("结算回调更新订单状态异常", e);
        }
    }
}
